package cn.four.hqServer.modules.account.service.impl;

import cn.four.hqServer.common.entity.*;
import cn.four.hqServer.common.enums.CardStatusEnum;
import cn.four.hqServer.common.enums.TranStatusEnum;
import cn.four.hqServer.modules.account.mapper.ZnbHqUserBalanceMapper;
import cn.four.hqServer.modules.account.service.ZnbIHqInterestRateService;
import cn.four.hqServer.modules.account.service.ZnbIHqInterestRecordService;
import cn.four.hqServer.modules.account.service.ZnbIHqUserBalanceService;
import cn.four.hqServer.modules.transfer.service.ZnbIHqCardInfoService;
import cn.four.hqServer.modules.transfer.service.ZnbIHqTranUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author znb
 * @since 2023-02-23
 */
@Service
public class HqUserBalanceServiceImpl extends ServiceImpl<ZnbHqUserBalanceMapper, HqUserBalance> implements ZnbIHqUserBalanceService {

    @Autowired
    private ZnbIHqCardInfoService cardInfoService;

    @Autowired
    private ZnbIHqInterestRecordService recordService;

    @Autowired
    private ZnbIHqInterestRateService rateService;

    @Autowired
    private ZnbIHqTranUserService tranUserService;





    @Override
    public boolean everyAdd() {
        //获取银行账户表list
        List<HqCardInfo> list = cardInfoService.list();
        List<HqUserBalance> res = new ArrayList<>();
        for (HqCardInfo hqCardInfo : list) {
            if(!hqCardInfo.getState().equals(CardStatusEnum.normal.getCode())){
               continue;
            }
            HqUserBalance userBalance = new HqUserBalance();
            userBalance.setCardId(hqCardInfo.getCardId());
            userBalance.setBalance(hqCardInfo.getBalance());
            userBalance.setBalanceDate(LocalDateTime.now());
            userBalance.setCreateTime(LocalDateTime.now());
            userBalance.setUpdateTime(LocalDateTime.now());

            res.add(userBalance);
        }
        this.saveBatch(res);
        return true;
    }

    /**
     * 结息
     * @return
     */
    @Override
    public boolean interest() {
        //获取当前时间
        LocalDateTime endTime = LocalDateTime.now();
        //查询每个转户的累计计息
        //1. 获取所有账号
        List<HqCardInfo> list = cardInfoService.list();
        for (HqCardInfo hqCardInfo : list) {
            //银行卡正常
            if(Objects.equals(hqCardInfo.getState(), CardStatusEnum.normal.getCode())){
                String cardId = hqCardInfo.getCardId();
                // 根据银行卡号获取上一次结息的时间
                HqInterestRecord record = recordService.getOne(new QueryWrapper<HqInterestRecord>().eq("card_id", cardId));
                LocalDateTime startTime;
                if(record == null){
                    //如果没有就是第一次存款的时间
                    startTime = hqCardInfo.getCreateTime();
                }else{
                    startTime = record.getTranTime();
                }
                //获取余额日记表中的数据
                List<HqUserBalance> balances = this.list(new QueryWrapper<HqUserBalance>()
                        .eq("card_id", cardId)
                        .ge("balance_date",startTime)
                        .le("balance_date",endTime));
                //总额
                BigDecimal total = new BigDecimal("0");
                for (HqUserBalance balance : balances) {
                    total = total.add(balance.getBalance());
                }
                //获取利率
                HqInterestRate interestRate;
                List<HqInterestRate> rates = rateService.list();
                interestRate = rates.get(0);
                Double rate = interestRate.getAnnualInterestRate() / 100.0;
                //计算利息
//                long l = Duration.between(startTime, endTime).toDays();
                BigDecimal totals = total.multiply(new BigDecimal(rate.toString()));
                BigDecimal totalRate = totals.divide(new BigDecimal("360"),20,BigDecimal.ROUND_HALF_UP);
                //记录结算利息记录表
                if(record == null){
                    record = new HqInterestRecord();
                    record.setCardId(cardId);
                    record.setInterestAmount(totalRate);
                    record.setTranTime(endTime);
                    recordService.save(record);
                }else {
                    record.setInterestAmount(totalRate);
                    recordService.updateById(record);
                }
                //记录用户账务交易流水表
                HqTranUser hqTranUser = new HqTranUser();
                hqTranUser.setCardId(cardId);
                hqTranUser.setBusinessType(TranStatusEnum.interest.getCode());
                hqTranUser.setTranAmount(totalRate);
                HqCardInfo cardInfo = cardInfoService.getById(cardId);
                hqTranUser.setTranAfterAmount(cardInfo.getBalance().add(totalRate));
                hqTranUser.setTranTime(endTime);
                hqTranUser.setTranName("银行账户");
                hqTranUser.setTranCardId("100000000000000001");

                tranUserService.save(hqTranUser);
                //将结算的利息增加到用户的存款余额
                cardInfo.setBalance(cardInfo.getBalance().add(totalRate));
                cardInfoService.updateById(cardInfo);
            }
        }
        return true;
    }

    @Override
    public boolean updateL(String lilu) {
        //设置利率
        HqInterestRate interestRate = new HqInterestRate();
        interestRate.setAnnualInterestRate(Double.parseDouble(lilu));
        interestRate.setCreateTime(LocalDateTime.now());
        interestRate.setUpdateTime(LocalDateTime.now());
        rateService.save(interestRate);
        return true;
    }
}
